<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">
      <div class="title-container">
        <h3 class="title">华龙航空综合财务</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <i class="el-icon-mobile-phone" />
        </span>
        <el-input ref="username" v-model.trim="loginForm.username" placeholder="手机号" name="username" type="text" tabindex="1" autocomplete="off" />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="18">
          <el-form-item prop="password">
            <span class="svg-container">
              <i class="el-icon-message" />
            </span>
            <el-input ref="captcha" v-model.trim="loginForm.captcha" type="text" placeholder="短信验证码" name="captcha" tabindex="2" autocomplete="off" @keyup.native="checkCapslock" @blur="capsTooltip = false" />
          </el-form-item>
        </el-col>
        <el-col :span="6" class="number-check">
          <span v-if="time" class="hint">{{ time }}s以后重新发送</span>
          <el-link v-else type="primary" @click="sendCaptcha">发送验证码</el-link>
        </el-col>
      </el-row>

      <el-button :loading="loading" type="primary" style="width: 100%; margin-top: 10px" @click.native.prevent="handleLogin">
        {{ $t('login.logIn') }}
      </el-button>
    </el-form>

    <el-dialog title="输入验证码" :visible.sync="dialogVisible" width="30%">
      <img :src="imgUrl" alt="验证码没有加载" />
      <!-- <span class="change-captcha">看不清， 换一个</span> -->
      <el-link class="change-captcha" @click="changeCaptcha">看不清， 换一个</el-link>
      <el-form ref="dataForm" :model="temp" :rules="tempRules">
        <el-form-item prop="captcha">
          <el-input v-model="temp.captcha" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sendSms">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCode, sendSms } from '@/api/user'
export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '13605706992',
        captcha: '1111'
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: '请输入手机号' }],
        captcha: [{ required: true, trigger: 'blur', validator: '请输入短信验证码 ' }]
      },
      capsTooltip: false,
      loading: false,
      redirect: undefined,
      otherQuery: {},
      // 图片验证码
      dialogVisible: false,
      imgUrl: '',
      temp: {
        captcha: '',
        code: '',
        mobile: ''
      },
      tempRules: {
        captcha: [
          { required: true, trigger: 'blur', message: '请输入验证码' },
          { min: 4, max: 4, message: '验证码长度 4 个字符', trigger: 'blur' }
        ]
      },
      time: 0
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    this.getCode()
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.captcha === '') {
      this.$refs.captcha.focus()
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && key >= 'A' && key <= 'Z'
    },
    sendCaptcha() {
      if (!this.loginForm.username) {
        this.$message.error('请先输入手机号')
        return
      }
      this.changeCaptcha()
      this.temp.captcha = ''
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    changeCaptcha() {
      this.imgUrl = process.env.VUE_APP_BASE_API + '/v1/captcha?code=' + this.temp.code + '&date=' + Date.now()
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true
          this.$store
            .dispatch('user/login', this.loginForm)
            .then(() => {
              console.log(222222222)
              this.$router.push({
                path: this.redirect || '/dashboard',
                query: this.otherQuery
              })
              this.loading = false
            })
            .catch(() => {
              console.log(1111111111)
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    // 获取系统唯一编码
    getCode() {
      getCode().then((response) => {
        this.temp.code = response.data.code
      })
    },
    sendSms() {
      this.dialogVisible = false
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const { code, captcha } = this.temp
          sendSms({ code, captcha, mobile: this.loginForm.username }).then((response) => {
            this.$message.success('短信验证码发送成功')
            this.dialogVisible = false
            this.time = 60
            this.countDown()
          })
        }
      })
    },
    countDown() {
      const timer = setInterval(() => {
        this.time--
        if (!this.time) clearInterval(timer)
      }, 1000)
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */
$bg: #283443;
$light_gray: #fff;
$cursor: #fff;
@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}
/* reset element-ui css */
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  background: url(~@/assets/imgs/login_bg.png) no-repeat center center;
  background-size: 100% 100%;
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;
    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;
      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }
  .number-check {
    color: #fff;
    padding-top: 15px;
    font-size: 14px;
    .hint {
      color: #ccc;
    }
  }
  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.2);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }

  .el-dialog {
    .el-form-item {
      background: #fff;
      border: 1px solid #ddd;
      color: #000;
      input {
        color: #000;
        caret-color: #000;
      }
    }
    .change-captcha {
      position: relative;
      top: -20px;
    }
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;
.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  .login-form {
    background: url(~@/assets/imgs/form_bg.png) no-repeat;
    position: relative;
    width: 580px;
    height: 404px;
    max-width: 100%;
    margin: 0 auto;
    overflow: hidden;
    padding: 70px;
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }
  .title-container {
    position: relative;
    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
